package com.xdcplus.web;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xdcplus.redis.RedisUtils;
import com.xdcplus.web.handler.PacketTraceWashHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 系统启动后操作
 */
@Slf4j
@Component
public class MesWebApiServiceRunner implements CommandLineRunner {


    @Value("${thread.size: 1}")
    protected Integer threadCount;

    @Autowired
    protected RedisUtils redisUtils;

    private static String keyTemplate = "snowflake_id#%s_%s";

    @Autowired
    private PacketTraceWashHandler packetTraceWashHandler;

    @Override
    public void run(String... args) throws Exception {
        log.info("算法因子注册中......");
        Random random = new Random();
        while (true) {
            try {
                int workId = random.nextInt(31);
                int dataCenterId = random.nextInt(31);
                /// 自定义mybatis id 算法因子，避免id冲突
                String key = String.format(keyTemplate, workId, dataCenterId);
                if (!redisUtils.hasKey(key)) {
                    IdWorker.initSequence(workId,dataCenterId);
                    redisUtils.setEx(key,1, 1, TimeUnit.DAYS);
                    log.info("算法因子注册成功,workId = {},dataCenterId = {}",workId,dataCenterId);
                    break;
                }
            }catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
    }


}
